<?php
/**
 * @author Created by dungtn
 * @version 1.0
 * @package Fdoc
 * @subpackage FdocSystem
 *
 */

define("_LABEL_LINK", "リンクはこちら");

class Vlib_TextCommon {

	/**
	 * instance object FDocTextCommon
	 *
	 * @var FDocTextCommon
	 */
	private static $_instance = null;

	/**
	 * Constructor method
	 *
	 */
	private function __construct(){

	}

	/**
	 * get Instance class
	 *
	 * @return FDocTextCommon
	 */
	public static function getInstance() {
		if (!isset(self::$_instance)) {
			$cls = __CLASS__;
			self::$_instance = new $cls();
		}
		return self::$_instance;
	}


	/**
	 * Convert break lines to <br /> tags
	 *
	 * @param string $text
	 * @return string
	 */
	public function nl2Br($text) {
		return preg_replace("/\r\n|\n|\r/", "<br />", $text);
	}

	/**
	 * Add slashes to content if magic_quotes_gpc is set off.
	 *
	 * @param string $text
	 * @return string
	 */
	public function addSlashes($text){
		if (get_magic_quotes_gpc() == 0) {
			$text = addslashes($text);
		}
		return $text;
	}

	/**
	 * strip back slashes in content if magic_quotes_gpc is set on
	 *
	 * @param string $text
	 * @return string
	 */
	function stripSlashes($text) {
		if (get_magic_quotes_gpc() == 1) {
			$text = stripslashes($text);
		}
		return $text;
	}

	/**
	 * Convert special characters to HTML entities
	 *
	 * @param string $text
	 * @return string
	 */
	public function htmls($text) {
		return htmlspecialchars($text, ENT_QUOTES);
	}

	/**
	 * Convert all HTML entities to their applicable characters
	 *
	 * @param string $text
	 * @return string
	 */
	public function unHtmls($text) {
		return html_entity_decode($str, ENT_QUOTES);
	}
	
	/**
	 * trim space character mulbyte
	 *
	 * @param string $str
	 * @param string $chars
	 * @return string
	 */
	public function mbTrim($str, $chars = '\s　') {
		$str = preg_replace("/^[$chars]+/u", '', $str);
		$str = preg_replace("/[$chars]+$/u", '', $str);
		return $str;
	}
	
	/**
	 * Strip HTML tag
	 *
	 * @param string $document
	 * @return string
	 */
	public function html2txt($document){
		$search = array('@<script[^>]*?>.*?</script>@si',  // Strip out javascript
		'@<[\\/\\!]*?[^<>]*?>@si',            // Strip out HTML tags
		'@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
		'@<![\\s\\S]*?--[ \\t\\n\\r]*>@'          // Strip multi-line comments including CDATA
		);
		$text = preg_replace($search, '', $document);
		return $text;
	}
	
	/**
	 * create link with URL
	 *
	 * @param string $str
	 * @return string
	 */
	public function linkURL($str, $mailOnly = false) {

		if (!$mailOnly) {
			$regex = "((https?://|ftp://)([0-9A-Za-z:_?./~%;()=+#-]|&amp;)+)";
			$str = eregi_replace($regex, "<a href=\"\\1\" target=\"_blank\">\\1</a>", $str);
		}
		
		$regex_mail = "((mailto:)?([0-9A-Za-z._-]+@[0-9A-Za-z.-]+))";
		$str = eregi_replace($regex_mail, "<a href=\"mailto:\\3\">\\1</a>", $str);

		return $str;
	}
	
	/**
	 * create link with URL
	 *
	 * @param string $str
	 * @return string
	 */
	public function linkURLShort($str, $mailOnly = false) {

		if (!$mailOnly) {
			$regex = "((https?://|ftp://)([0-9A-Za-z:_?./~%;()=+#-]|&amp;)+)";
			$str = eregi_replace($regex, "<a href=\"\\1\" target=\"_blank\" title=\"\\1\">"._LABEL_LINK."</a>", $str);
		}
		
		$regex_mail = "((mailto:)?([0-9A-Za-z._-]+@[0-9A-Za-z.-]+))";
		$str = eregi_replace($regex_mail, "<a href=\"mailto:\\3\">\\1</a>", $str);

		return $str;
	}
	
	/**
	 * Truncate string to max length
	 *
	 * @param String $str
	 * @param Integer $maxLen
	 * @param String $replaceStr
	 * @param String $charset
	 * @return String
	 */
	public function mbTextTruncate ($str, $maxLen, $replaceStr = '。。。', $charset = 'UTF-8') {
		$intStrLen = mb_strlen($str, $charset);
		if($intStrLen <= $maxLen) return $str;

		$str = mb_substr($str, 0, $maxLen - mb_strlen($replaceStr, $charset), $charset);
		$str .= $replaceStr;		
		return $str;
	}
	
	/**
	 * filters value for CSV content
	 *
	 * @param string $val
	 * @return string
	 */
	public function filterCSV($val) {
		if (!$val)
			return;
		
		$ret = $val;

		if (preg_match("/,|\"|\r\n|\n/", $ret)) {
			$ret = preg_replace('/"/', '""', $ret);
		}
		$ret = '"' . $ret . '"';

		return $ret;
	}
    
    /** 
     * Sanitize insert text data
     * @param string $str
     * @return string
     */
    private function _it($str)
    {
        $_str = $str;
        $_str = stripslashes($_str);
        $_str = addslashes($_str);
        return $_str;
    }

    /**
     * Sanitize insert text data
     *　correspondence array
     * @param mixed {string or array}
     * @return mixed {string or array}
     */
    public function it($mixed)
    {
        //配列判定
        if (is_array($mixed)) {
            $_arr = array();
            //ループ
            foreach ($mixed as $v) {
                $_arr[] = self::_it($v);
            }
            return $_arr;
        }
        else {
            return self::_it($mixed);
        }
    }
    
    /**
     * @desc remove all the comment from sql string
     * 
     * @author Tuyendn<tuyendn@vnext.vn>
     */
    function removeComments(&$output) {
        $lines = explode("\n", $output);
        $output = "";

        // try to keep mem. use down
        $linecount = count($lines);

        $in_comment = false;
        for ($i = 0; $i < $linecount; $i++) {
            if (preg_match("/^\/\*/", preg_quote($lines[$i]))) {
                $in_comment = true;
            }

            if (!$in_comment) {
                $output .= $lines[$i] . "\n";
            }

            if (preg_match("/\*\/$/", preg_quote($lines[$i]))) {
                $in_comment = false;
            }
        }

        unset($lines);
        return $output;
    }

    /**
     * @desc remove_remarks will strip the sql comment lines out of an uploaded sql file
     * 
     * @author Tuyendn<tuyendn@vnext.vn>
     */
    function removeRemarks($sql) {
        $lines = explode("\n", $sql);

        // try to keep mem. use down
        $sql = "";

        $linecount = count($lines);
        $output = "";

        for ($i = 0; $i < $linecount; $i++) {
            if (($i != ($linecount - 1)) || (strlen($lines[$i]) > 0)) {
                if (isset($lines[$i][0]) && $lines[$i][0] != "#") {
                    $output .= $lines[$i] . "\n";
                } else {
                    $output .= "\n";
                }
                // Trading a bit of speed for lower mem. use here.
                $lines[$i] = "";
            }
        }

        return $output;
    }

     /**
     * @desc: Check date string is compatible with format yyyy/mm/dd
     * 
     * @author trunghpb
     * @copyright: Tran Nghia <nghiat@vnext.vn>
     * @since: 2012/03/03
    */
     public function isValidDateFormat($date) {
        $result = false;
        // If data is null
        if (!$date) {
            return true;    // do not test
        }
        // Match the format of the date
        if (preg_match("/^([0-9]{4})\/([0-9]{2})\/([0-9]{2})$/", $date, $parts)) {
            // Check weather the date is valid of not
            $result = checkdate($parts[2], $parts[3], $parts[1]);
        }

        return $result;
    }
    
    /*
     * @desc split_sql_file will split an uploaded sql file into single sql statements.
     * Note: expects trim() to have already been run on $sql.
     *
     * @author Tuyendn<tuyendn@vnext.vn>
     */
    function splitSqlFile($sql, $delimiter) {
        // Split up our string into "possible" SQL statements.
        $tokens = explode($delimiter, $sql);

        // try to save mem.
        $sql = "";
        $output = array();

        // we don't actually care about the matches preg gives us.
        $matches = array();

        // this is faster than calling count($oktens) every time thru the loop.
        $token_count = count($tokens);
        for ($i = 0; $i < $token_count; $i++) {
            // Don't wanna add an empty string as the last thing in the array.
            if (($i != ($token_count - 1)) || (strlen($tokens[$i] > 0))) {
                // This is the total number of single quotes in the token.
                $total_quotes = preg_match_all("/'/", $tokens[$i], $matches);
                // Counts single quotes that are preceded by an odd number of backslashes,
                // which means they're escaped quotes.
                $escaped_quotes = preg_match_all("/(?<!\\\\)(\\\\\\\\)*\\\\'/", $tokens[$i], $matches);

                $unescaped_quotes = $total_quotes - $escaped_quotes;

                // If the number of unescaped quotes is even, then the delimiter did NOT occur inside a string literal.
                if (($unescaped_quotes % 2) == 0) {
                    // It's a complete sql statement.
                    $output[] = $tokens[$i];
                    // save memory.
                    $tokens[$i] = "";
                } else {
                    // incomplete sql statement. keep adding tokens until we have a complete one.
                    // $temp will hold what we have so far.
                    $temp = $tokens[$i] . $delimiter;
                    // save memory..
                    $tokens[$i] = "";

                    // Do we have a complete statement yet?
                    $complete_stmt = false;

                    for ($j = $i + 1; (!$complete_stmt && ($j < $token_count)); $j++) {
                        // This is the total number of single quotes in the token.
                        $total_quotes = preg_match_all("/'/", $tokens[$j], $matches);
                        // Counts single quotes that are preceded by an odd number of backslashes,
                        // which means they're escaped quotes.
                        $escaped_quotes = preg_match_all("/(?<!\\\\)(\\\\\\\\)*\\\\'/", $tokens[$j], $matches);

                        $unescaped_quotes = $total_quotes - $escaped_quotes;

                        if (($unescaped_quotes % 2) == 1) {
                            // odd number of unescaped quotes. In combination with the previous incomplete
                            // statement(s), we now have a complete statement. (2 odds always make an even)
                            $output[] = $temp . $tokens[$j];

                            // save memory.
                            $tokens[$j] = "";
                            $temp = "";

                            // exit the loop.
                            $complete_stmt = true;
                            // make sure the outer loop continues at the right point.
                            $i = $j;
                        } else {
                            // even number of unescaped quotes. We still don't have a complete statement.
                            // (1 odd and 1 even always make an odd)
                            $temp .= $tokens[$j] . $delimiter;
                            // save memory.
                            $tokens[$j] = "";
                        }
                    } // for..
                } // else
            }
        }

        return $output;
    }

}
